package com.app.util.common;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;


/**
 * 常见的string 操作
 * 常见的object 操作
 * @author chenl
 *
 */
public class ObjUtil {

	/**
	 * 判断数组中是否存在
	 * @param value
	 * @param array
	 * @return
	 */
	public static boolean checkExistInArray(String value,String[] array) {
		if(value == null || array == null || array.length == 0) {
			return false;
		}
		for(String temp : array) {
			if(temp.equals(value)) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 判断list中是否存在
	 * @param key
	 * @param list
	 * @return
	 */
	public static boolean checkExistInList(Object obj,List<?> list){
		return list.contains(obj);
	}
	
	/**
	 * 将字符串转化成相应类型
	 * @param c
	 * @param value
	 * @return
	 */
	public static Object strToObject(Class<?> c,String value) {
		if(value == null) {
			return null;
		}
		if(c == java.lang.String.class) {
			return value;
		}
		if(c == java.util.Date.class) {
			if(value == null || value.equals("")) {
				return null;
			}
			return Format.getDate(value);
		}
		if(c == java.lang.Integer.class || c == int.class) {
			if(value == null || value.equals("")) {
				return null;
			}
			try {
				return Integer.parseInt(value); 
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		}
		if(c == java.lang.Double.class || c == double.class) {
			if(value == null || value.equals("")) {
				return null;
			}
			try {
				return Double.parseDouble(value);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		if(c == java.lang.Float.class || c == float.class) {
			if(value == null || value.equals("")) {
				return null;
			}
			try {
				return Float.parseFloat(value);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		if(c == java.lang.Long.class || c == long.class) {
			if(value == null || value.equals("")) {
				return null;
			}
			try {
				return Long.parseLong(value);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		}
		if(c == String[].class) {
			return ((String) value).split(",");
		}
		return null;
	}
	
	
	
	
	
	
	/**
	 * 获取对象值
	 * @param list
	 * @param fieldName
	 */
	public static Object getFieldValues(Object obj,String fieldName){
		return ReflectionUtil.getFieldValue(obj, fieldName);
	}
	
	/**
	 * 将list对象中的fieldName属性值获取并拼接成字符串
	 * @param list
	 * @param fieldName
	 */
	public static String getFieldValues(List<?> list,String fieldName){
		return ReflectionUtil.getFieldValues(list, fieldName);
	}
	
	/**
	 * 对象赋值
	 * @param list
	 * @param fieldName
	 */
	public static void setFieldValues(Object obj,String fieldName,Object value){
		ReflectionUtil.setFieldValue(obj, fieldName, value);
	}
	
	/**
	 * 获取list中某一属性值，并将其封装成sql字符串
	 * @param list
	 * @param fieldName
	 * @return
	 */
	public static String getSqlFieldValues(List<?> list,String fieldName){
		return strToSql(getFieldValues(list, fieldName));
	}
	
	/**
	 * 从list中获取对象的某一个属性，并以list返回
	 * @param list
	 * @param fieldName
	 * @return
	 */
	public static List<String> getFieldValuesToList(List<?> list, String fieldName) {
		// TODO Auto-generated method stub
		String values = getFieldValues(list, fieldName);
		if(values == null || values.equals("")) {
			return new ArrayList<String>();
		}
		String[] array = values.split(",");
		List<String> listString = new ArrayList<String>();
		for(String value :array) {
			listString.add(value);
		}
		return listString;
	}
	
	/**
	 * 去空格
	 * @param value
	 * @return
	 */
	public static String trim(String value) {
		if(value == null) {
			return null;
		}
		return value.replaceAll("\\s*", "");
	}
	
	
	//效验 参数中是否存在sql注入 
    public static boolean sqlValidate(String str) {  
        str = str == null ?"" :str.toLowerCase();//统一转为小写  
        
        String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +  
                "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +  
                "table|from|grant|use|group_concat|column_name|" +  
                "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +  
                "chr|mid|master|truncate|char|declare|or|;|-|--|+|like|//|/|%|#";//过滤掉的sql关键字，可以手动添加  
        String[] badStrs = badStr.split("\\|");  
        for (int i = 0; i < badStrs.length; i++) {  
            if (str.equals(badStrs[i])) {  
                return true;  
            }  
        }  
        return false;  
    }  
    
    /**
     * 验证带有空格字符串的数据是否有sql注入
     * true表示有sql注入的关键词
     * @param value
     */
    public static boolean sqlValidateWithSpace(String value) {
    	if(value == null || value.equals("")) {
    		return false;
    	}
    	String[] arr = splitBySpace(value);
    	
    	boolean flag = false;
    	for(int i=0;i<arr.length;i++){
    		flag = flag ||sqlValidate(arr[i]);
    	}
    	return flag;
    }
    
    /**
     * 以空格字符串进行分割
     * @param value
     * @return
     */
    public static String[] splitBySpace(String value) {
    	if(value == null) {
    		return null;
    	}
    	String [] arr = value.split("\\s+");
    	return arr;
    }

    /**
     * 在existList对象fieldName属性中比较newIds挑选新加入的元素
     * @param existList	基础对象
     * @param fieldName list中对象的属性
     * @param newIds  用于保存最新的数据	
     * @return
     */
    @SuppressWarnings( {"rawtypes"} )
	public static String[] compareWithAdd(List<?> existList, String fieldName, String[] newIds) {
		// TODO Auto-generated method stub
		if(existList == null || existList.size() == 0) {
			return newIds;
		}
		List<String> existValueList = new ArrayList<String>();
		for(int i=0;i<existList.size();i++) {
			Object obj = existList.get(i);
			String objValue = "";
			if(obj instanceof String) {
				objValue = (String)obj;
			}else if(obj instanceof Map) {
				objValue = (String) ((Map)obj).get(fieldName);
			}else {
				objValue = (String)getFieldValues(obj, fieldName);
			}
			existValueList.add(objValue);
		}
		List<String> diffIds = new ArrayList<String>();
		for(int i=0;newIds!=null&&i<newIds.length;i++) {
			if(!existValueList.contains(newIds[i])) {
				diffIds.add(newIds[i]);
			}
		}
		String[] resultArr = new String[diffIds.size()];
		for(int i=0;i<diffIds.size();i++) {
			resultArr[i] = diffIds.get(i);
		}
		return resultArr;
	}
    
    /**
     * 将数组转list
     * @param arr
     * @return
     */
    public static <T> List<T> arrToList(T[] arr){
    	List<T> list = new ArrayList<T>();
    	
    	for(int i=0;arr!=null && i<arr.length;i++) {
    		list.add(arr[i]);
    	}
    	
    	return list;
    }
    
	/**
     * 在existList对象fieldName属性中比较newIds挑选新加入的元素
     * @param existList	基础对象
     * @param fieldName list中对象的属性
     * @param newIds  用于保存最新的数据	
     * @return
     */
	@SuppressWarnings( {"rawtypes","unchecked"} )
	public static <T> List<T> compareWithDel(List<T> existList, String fieldName, String[] newIds) {
		// TODO Auto-generated method stub
		List delList = new ArrayList();
		if(existList == null || existList.size() == 0) {
			return delList;
		}
		if(newIds == null || newIds.length == 0) {
			return existList;
		}
		List<String> newIds_list = new ArrayList<String>(Arrays.asList(newIds));
		
		
		for(int i=0;i<existList.size();i++) {
			Object obj = existList.get(i);
			String objValue = "";
			if(obj instanceof String) {
				objValue = (String)obj;
			}else if(obj instanceof Map) {
				objValue = (String) ((Map)obj).get(fieldName);
			}else {
				objValue = (String)getFieldValues(obj, fieldName);
			}
			if(!newIds_list.contains(objValue)) {
				delList.add(existList.get(i));
			}
		}
		return delList;
		
	}

	/**
	 * 将对象封装成一个树形结构，并返回最顶级的list集合
	 * @param list				对象集合
	 * @param strIdField		对象的ID属性名
	 * @param strParentIdField	对象的父级关联属性名
	 * @param childrenField		用于存储对象子集合的属性名
	 */
	@SuppressWarnings({"rawtypes","unchecked"})
	public static <T> List<T> toTree(List<T> listExist, String strIdField, String strParentIdField, String childrenField) {
		// TODO Auto-generated method stub
		if(listExist == null) {
			return null;
		}
		List newList = new ArrayList();
		for(int i=0;i<listExist.size();i++) {
			try {
				T t = (T)BeanUtils.cloneBean(listExist.get(i));
				newList.add(t);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		
		List rootList = new ArrayList();
		//将对象暂存
		Map<String,Object> map = new HashMap<String,Object>();
		for(int i=0;i<newList.size();i++) {
			Object obj = newList.get(i);
			map.put((String)getFieldValues(obj, strIdField), obj);
		}
		
		for(int i=0;i<newList.size();i++) {
			Object obj = newList.get(i);
			String strParentId = (String)getFieldValues(obj, strParentIdField);
			if(strParentId != null) {
				Object objParent = map.get(strParentId);
				if(objParent != null) {	//找到上级
					List children = (List)getFieldValues(objParent, childrenField);
					if(children == null) {
						children = new ArrayList();
					}
					children.add(obj);
					ReflectionUtil.setFieldValue(objParent, childrenField, children);
				}else {
					rootList.add(obj);
				}
			}else {
				rootList.add(obj);
			}
		}
		return rootList;
	}
	
	

	
	/**
	 * 将以“,"连接的字符串，转成sql拼接
	 * @param str
	 * @return
	 */
	public static String strToSql(String str){
		StringBuffer result = new StringBuffer();
		if(str == null || str.equals("")){
			return "";
		}
		String[] arr = str.split(",");
		
		for(int i=0;i<arr.length;i++){
			result.append("'"+arr[i]+"'");
			if(i != arr.length-1){
				result.append(",");
			}
		}
		return result.toString();
	}
	
	/**
	 * 将字符串list，转成sql拼接
	 * @param str
	 * @return
	 */
	public static String listToSql(List<String> strList){
		String result = "";
		if(strList == null){
			return "";
		}
		
		for(int i=0;i<strList.size();i++){
			result += "'"+strList.get(i)+"'";
			if(i != strList.size()-1){
				result += ",";
			}
		}
		return result;
	}
	
	/**
	 * 将字符串list，转成字符串拼接,并以","连接
	 * @param str
	 * @return
	 */
	public static String listToString(List<String> strList){
		String result = "";
		if(strList == null){
			return "";
		}
		
		for(int i=0;i<strList.size();i++){
			result += strList.get(i);
			if(i != strList.size()-1){
				result += ",";
			}
		}
		return result;
	}
	
	
	/**
	 * 将字符串Array，转成sql拼接
	 * @param str
	 * @return
	 */
	public static String arrToSql(String[] array){
		String result = "";
		if(array == null){
			return "";
		}
		for(int i=0;i<array.length;i++){
			result += ("'"+array[i]+"'");
			if(i != array.length-1){
				result += ",";
			}
		}
		return result;
	}
	
	/**
	 * 将Array转成String
	 * @param str
	 * @return
	 */
	public static String arrToStr(String[] array){
		String result = "";
		if(array == null){
			return "";
		}
		for(int i=0;i<array.length;i++){
			result += ""+array[i]+"";
			if(i != array.length-1){
				result += ",";
			}
		}
		return result;
	}
	
	/**
	 * 字符串转list
	 * @param str
	 * @return
	 */
	public static List<String> strToList(String str){
		List<String> result = new ArrayList<String>();
		if(str == null || str.equals("")){
			return result;
		}
		String[] arr = str.split(",");
		for(int i=0;i<arr.length;i++){
			result.add(arr[i]);
		}
		return result;
	}
	
	/**
	 * 获取集合中对象指定属性，并返回集合
	 * @param list
	 * @param string
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> creatList(List<T> list, String... fieldNames) {
		// TODO Auto-generated method stub
		if(list == null) {
			return null;
		}
		if(fieldNames == null || fieldNames.length == 0) {
			return list;
		}
		List<T> newList = new ArrayList<T>();
		
		for(int i=0;i<list.size();i++) {
			T t = list.get(i);
			try {
				T newT = (T)t.getClass().newInstance();
				for(int a=0;a<fieldNames.length;a++) {
					String fieldName = fieldNames[a];
					setFieldValues(newT, fieldName, getFieldValues(t, fieldName));
				}
				newList.add(newT);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return newList;
	}
	
	/**
	 * 将list对象中的fieldName属性,按map对象中key，value进行替换
	 * @param list
	 * @param map
	 */
	@SuppressWarnings("rawtypes")
	public static void matchParam( List list,String fieldName,Map<String,String> map) {
		if(map == null) {
			return;
		}
		if(list != null) {
			for(int i=0;i<list.size();i++) {
				String value = (String)getFieldValues(list.get(i), fieldName);
				if(value != null && !value.equals("")) {
					String newValue = map.get(value);
					if(newValue != null) {
						setFieldValues(list.get(i), fieldName, newValue);
					}
				}
			}
		}
		
		
	}
	
	/**
	 * 将list按其泛型对象中的属性，分割成一个map，以fieldName的value为标准来分组
	 * @param caseDistList
	 * @param string
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> Map<String, List<T>> listToMapByField(List<T> list, String fieldName) {
		// TODO Auto-generated method stub
		
		Map<String,List<T>> map = new HashMap<String,List<T>>();
		
		for(int i=0,len = list==null?0:list.size();i<len;i++) {
			T obj = list.get(i);
			//获取fieldName的值
			String fieldValue = (String)getFieldValues(obj, fieldName);
			
			List tempList = map.get(fieldValue);
			if(tempList == null) {
				tempList = new ArrayList();
			}
			tempList.add(obj);
			map.put(fieldValue+"", tempList);
			
		}
		
		return map;
	}
	
	
	/**
	 * 将list按其泛型对象中的属性，分割成一个map，以fieldName的value为标准来分组
	 * @param caseDistList
	 * @param string
	 * @return
	 */
	public static <T> Map<String, T> listToObjMapByField(List<T> list, String fieldName) {
		// TODO Auto-generated method stub
		
		Map<String,T> map = new HashMap<String,T>();
		
		for(int i=0,len = list==null?0:list.size();i<len;i++) {
			T obj = list.get(i);
			//获取fieldName的值
			String fieldValue = (String)getFieldValues(obj, fieldName);
			
			map.put(fieldValue, obj);
			
		}
		
		return map;
	}
	
	
	/** 
     * 直接调用对象方法, 而忽略修饰符(private, protected, default) 
     * @param object : 子类对象 
     * @param methodName : 父类中的方法名 
     * @param parameterTypes : 父类中的方法参数类型 
     * @param parameters : 父类中的方法参数 
     * @return 父类中方法的执行结果 
     */  
      
    public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,  
            Object [] parameters) {  
		return ReflectionUtil.invokeMethod(object, methodName, parameterTypes, parameters);
	}
	
    public static Object invokeStaticMethod(String className,String methodName,Class<?>[] c,Object[] obj) throws Exception{
	    return ReflectionUtil.invokeStaticMethod(className, methodName, c, obj)  ;
    }
    
    /**
     * 将list进行重新排序
     * @param list
     * @param fieldName
     * @param sortType
     */
    public static <T> void sortList(List<T> list,String fieldName,String sortType) {
    	    	
    	Collections.sort(list, new Comparator<T>(){
    		 
            @Override
            public int compare(T o1, T o2) {
            	Object objValue1 = ObjUtil.getFieldValues(o1, fieldName);
            	Object objValue2 = ObjUtil.getFieldValues(o2, fieldName);
            	
            	int result = compareObj(objValue1,objValue2);
            	int index = 1;
            	if(sortType != null && sortType.equalsIgnoreCase("desc")) {
            		index = -1;
            	}
            	return result * index;
            }          
        });
    }
    
    
    public static int compareObj(Object obj1,Object obj2) {
    	
    	if(obj1 == null && obj2 == null) {
    		return 0;
    	}else if(obj1 == null && obj2 != null) {
    		return -1;
    	}else if(obj1 !=null && obj2 == null) {
    		return 1;
    	}
    	
    	if(obj1 instanceof java.lang.Integer ) {
    		if( (Integer)obj1 > (Integer)obj2 ) {
    			return 1;
    		}else if((Integer)obj1 < (Integer)obj2) {
    			return -1;
    		}else {
    			return 0;
    		}
    	}else if(obj1 instanceof java.lang.Double) {
    		if( (Double)obj1 > (Double)obj2 ) {
    			return 1;
    		}else if((Double)obj1 < (Double)obj2) {
    			return -1;
    		}else {
    			return 0;
    		}
    	}else if(obj1 instanceof java.lang.Long) {
    		if( (Long)obj1 > (Long)obj2 ) {
    			return 1;
    		}else if((Long)obj1 < (Long)obj2) {
    			return -1;
    		}else {
    			return 0;
    		}
    	}else if(obj1 instanceof java.lang.Float) {
    		if( (Float)obj1 > (Float)obj2 ) {
    			return 1;
    		}else if((Float)obj1 < (Float)obj2) {
    			return -1;
    		}else {
    			return 0;
    		}
    	}else if(obj1 instanceof java.lang.Byte) {
    		if( (Byte)obj1 > (Byte)obj2 ) {
    			return 1;
    		}else if((Byte)obj1 < (Byte)obj2) {
    			return -1;
    		}else {
    			return 0;
    		}
    	}else if(obj1 instanceof java.lang.String) {
    		
    		return ((String)obj1).compareTo((String)obj2);
    		
    	}else if(obj1 instanceof java.util.Date) {
    		long diff = ((Date)obj1).getTime() - ((Date)obj2).getTime() ;
    		if(diff > 0) {
    			return 1;
    		}else if(diff == 0 ) {
    			return 0;
    		}else {
    			return -1;
    		}
    	}
    	
    	return -1;
    	
    }
	
    
    
    public static double formatDouble(double value,int fix) {
    	BigDecimal format = new BigDecimal(value);    
    	
    	return format.setScale(fix, BigDecimal.ROUND_HALF_UP).doubleValue(); 
 
    }
    
	public static String objToStr(Object obj) {
		// TODO Auto-generated method stub
		if(obj == null) {
			return null;
		}
		Class<?> c = obj.getClass();
		if(c == java.lang.String.class) {
			return (String)obj;
		}
		if(c == java.util.Date.class) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return format.format((Date)obj);
		}
		if(c == java.lang.Integer.class || c == int.class) {
			
			return String.valueOf(obj);
			
		}
		if(c == java.lang.Double.class || c == double.class) {
			return String.valueOf(obj);
		}
		if(c == java.lang.Float.class || c == float.class) {
			return String.valueOf(obj);
		}
		if(c == java.lang.Long.class || c == long.class) {
			return String.valueOf(obj);
			
		}

		return null;
		
	}
	
	/**
	 * 将字符串以“，”进行多少数量的分割，并以list返回每组
	 * @param value
	 * @param num
	 * @return
	 */
	public static List<String> splitToList(String value,int num){
		List<String> list = new ArrayList<String>();
		
		if(value == null || value.equals("") || num == 0) {
			return list;
		}
		
		String[] values = value.split(",");
		List<String> valueList = ObjUtil.arrToList(values);
		
		int allPage = (values.length - 1)/num + 1;
		
		for(int i=1;i<=allPage;i++) {
			int begin = (i-1)*num;
			int end = (i-1)*num + num;
			if(end > values.length) {
				end = values.length;
			}
			List<String> tempList = valueList.subList(begin, end);
			list.add(ObjUtil.listToString(tempList));
		}
		
		//计算分组情况
		
		
		return list;
	}
	
	
	public static void main(String[] args) {
		
		String str = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
		
		List<String> list = ObjUtil.splitToList(str, 10);
		for(int i=0;i<list.size();i++) {
			String temp = list.get(i);
			System.out.println("---"+temp);
		}
	}
	
    
}
